import { defineStore } from "pinia";
import { ref, toRaw, Ref } from "vue";
import { getReturnUrl } from "../utils/loadVideo";
// @ts-ignore
import { Combinator } from "../../@webav/av-cliper/dist/av-cliper.js";
import { events } from "../assets/bus";
import type sprType from "../type/spr.d";
import type videoConfig from "../type/sprConfig";

export const useTimelineStore = defineStore("timeline", () => {
  const timeline: Ref<Array<Array<sprType>>> = ref([[]]);
  const TEMPURL = ref("");

  let current: Ref<sprType> = ref({} as sprType);
  let dragged: sprType = {} as sprType;
  let currentIndex: Array<number> = [];
  async function addVideo(spr: sprType, config: videoConfig, index: number) {
    // if (timeline.value.every((l) => l.length == 0)) config.main = true;
    timeline.value[index].push({
      spr,
      config,
      animate: {},
    });
  }

  function cleanNullDeep(obj: Record<string, Record<string, string | number>>) {
    if (!obj) return obj;
    let temp: Record<string, Record<string, number>> = {};
    const sortKey = Object.keys(obj).sort((a, b) => parseInt(a) - parseInt(b));
    for (let step of sortKey) {
      for (let attr of Object.keys(obj[step])) {
        if (obj[step][attr] != "") {
          if (!temp[step]) temp[step] = {};
          temp[step][attr] = ~~obj[step][attr];
        }
      }
    }
    return temp;
  }
  function cleanNull(obj: Record<string, string | number>) {
    let temp: Record<string, number> = {};
    for (let attr of Object.keys(obj)) {
      if (obj[attr]) {
        temp[attr] = ~~obj[attr];
      }
    }
    return temp;
  }
  async function createVideo() {
    try {
      events.emit("start-create-video", { type: "text", msg: `创建画布` });
      let TEMPCOM = new Combinator({ width: 518, height: 920 });
      events.emit("start-create-video", { type: "text", msg: `添加元素` });
      for (let line of timeline.value) {
        for (let video of line) {
          let TEMPSPR = toRaw(await video.spr.reLoad());
          if (Object.keys(video.animate.data || {}).length) {
            TEMPSPR.setAnimation(
              cleanNullDeep(toRaw(video.animate.data!)),
              cleanNull(toRaw(video.animate.config!))
            );
            console.log(video.animate.config);
            if (!video.animate.config!.duration)
              // @ts-ignore
              window.$message.warning(
                "动画没有设置持续时间duration，将不会生效"
              );
            if (!video.animate.config!.iterCount)
              // @ts-ignore
              window.$message.warning(
                "动画没有设置次数iterCount，可能不会生效"
              );
          }

          await TEMPCOM.add(TEMPSPR, video.config);
        }
      }
      TEMPCOM?.on("OutputProgress", (v: number) => {
        events.emit("start-create-video", {
          type: "progress",
          msg: `demuxcode progress：${(v * 100).toFixed(3)}%`,
          value: v,
        });
      });

      // const spr2 = new OffscreenSprite(
      //   "t1",
      //   new TextClip("666", {
      //     videoWidth: 518,
      //     videoHeight: 920,
      //     fontSize: 44,
      //     fontFamily: "Noto Sans SC",
      //     strokeStyle: "#000",
      //     lineWidth: 20,
      //     lineJoin: "round",
      //     lineCap: "round",
      //     textShadow: {
      //       offsetX: 2,
      //       offsetY: 2,
      //       blur: 4,
      //       color: "rgba(0,0,0,0.25)",
      //     },
      //     position: {
      //       x: 50,
      //       y: 300,
      //     },
      //   })
      // );
      // TEMPCOM.add(spr2, { duration: 3, offset: 2 });
      getReturnUrl(TEMPCOM).then((res) => {
        TEMPURL.value = res;
        events.emit("end-create-video");
      });
    } catch (e) {
      events.emit("end-create-video");
      throw e;
    }
  }

  function addLine() {
    timeline.value.push([]);
    console.log(timeline.value);
  }
  function deleteVideo() {
    if (
      current.value &&
      toRaw(current.value) ==
        toRaw(timeline.value[currentIndex[0]][currentIndex[1]])
    )
      timeline.value[currentIndex[0]].splice(currentIndex[1], 1);
  }
  function setCurrent(lineIndex: number, index: number) {
    current.value = timeline.value[lineIndex][index];
    currentIndex = [lineIndex, index];
  }
  return {
    timeline,
    addVideo,
    dragged,
    currentIndex,
    TEMPURL,
    addLine,
    createVideo,
    current,
    deleteVideo,
    setCurrent,
  };
});
